package com.wxy.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.wxy.common.R;
import com.wxy.domain.Exam;
import com.wxy.domain.Student;
import com.wxy.domain.StudentExam;
import com.wxy.service.ExamService;
import com.wxy.service.StudentExamService;
import com.wxy.service.StudentService;
import com.wxy.service.TeacherService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/exam")
public class ExamController {
    @Autowired
    private TeacherService teacherService;

    @Autowired
    private ExamService examService;

    @Autowired
    private StudentExamService studentExamService;

    @Autowired
    private StudentService studentService;

    @PostMapping
    public R<String>publishExam(HttpServletRequest request, @RequestBody Exam exam){
        Long tusername = (Long) request.getSession().getAttribute("teacher");
        if (tusername == null)
            return R.error("您当前还没有这个权限!");
        exam.setTusername(tusername);
        examService.save(exam);

        //发布到每个学生的中去
        StudentExam studentExam = new StudentExam();
        LambdaQueryWrapper<Student> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(Student::getTusername,tusername);
        List<Student> stuList= studentService.list(queryWrapper);
        studentExam.setExamId(exam.getExamId());
        studentExam.setExamName(exam.getExamName());
        studentExam.setTusername(tusername);
        studentExam.setEndTime(exam.getEndTime());
        for(Student stu : stuList){
            studentExam.setSusername(stu.getSusername());
            studentExamService.save(studentExam);
        }
        return R.success("发布成功!");
    }
    public int verify(HttpServletRequest request){
        //学生
        Long userid1 = (Long) request.getSession().getAttribute("student");
        if (userid1 != null)
            return 1;
        //老师
        Long userid2 = (Long) request.getSession().getAttribute("teacher");
        if (userid2 != null)
            return 2;
        //管理员
        String root  = (String) request.getSession().getAttribute("root");
        if (root != null)
            return 3;
        return -1;
    }

    /**
     * 学生获取订阅信息
     * @param request
     * @return
     */
    @GetMapping("/student")
    public R<List<StudentExam>>subscribeExam(HttpServletRequest request){
        if(verify(request) == 1){
            Long userid1 = (Long) request.getSession().getAttribute("student");
            LambdaQueryWrapper<StudentExam> queryWrapper = new LambdaQueryWrapper();
            queryWrapper.eq(StudentExam::getSusername,userid1);
            List<StudentExam> list = studentExamService.list(queryWrapper);
            return R.success(list);
        }
        return R.success(null);
    }
    //老师查看学生实验并获得实验的完成进度
    @GetMapping("/teacher")
    public R<List<JSONObject>> TchReadExam(HttpServletRequest request){
        LambdaQueryWrapper<Exam> queryWrapper = new LambdaQueryWrapper();
        Long tusername = (Long) request.getSession().getAttribute("teacher");
        queryWrapper.eq(Exam::getTusername,tusername);
        List<Exam> list = examService.list(queryWrapper);
        if (list == null)
            return R.error(null);
        List<JSONObject> strings = new ArrayList<>();
        JSONObject json = new JSONObject();
        for (Exam exam : list){
            List<Map<String, Object>> maps = studentExamService.countStu(exam.getExamId());
            LambdaQueryWrapper<StudentExam> queryWrapper1 = new LambdaQueryWrapper();
            queryWrapper1.eq(StudentExam::getExamId,exam.getExamId());
            List<StudentExam> list1 = studentExamService.list(queryWrapper1);
            Long sum = (Long) maps.get(0).get("sum");
            Long sum1 = (Long) maps.get(1).get("sum1");
            if (sum == 0)
                continue;
            double baifenbi = (double) sum1 / (double) sum;
            json.put("examName",exam.getExamName());
            json.put("examId",exam.getExamId().toString());
            json.put("result",String.format("%.2f", baifenbi * 100) + "%");
            json.put("data",list1);
            strings.add(json);
        }
        return R.success(strings);
    }
    @PostMapping("/submit")
    public R<String>submit(HttpServletRequest request,@RequestBody StudentExam exam){
        Long susername = (Long) request.getSession().getAttribute("student");
        if (susername == null)
            return R.error("未登录!");
        LambdaQueryWrapper<StudentExam>queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(StudentExam::getSusername,susername)
                .eq(StudentExam::getExamId,exam.getExamId());
        StudentExam one = studentExamService.getOne(queryWrapper);
        log.info(one.toString());
        if (LocalDate.now().isAfter(one.getEndTime()))
            return R.error("已经超过时间了，无法提交！");
        one.setStatus(1);
        one.setPlantId(exam.getPlantId());
        one.setSubmitTime(LocalDate.now());
        studentExamService.update(one,queryWrapper);
        return R.success("提交成功!");
    }

    /**
     * 老师批改实验进行打分
     * @param request
     * @param exam
     * @return
     */
    @PostMapping("/correcting")
    public R<String>correct(HttpServletRequest request,@RequestBody StudentExam exam){
        Long tusername = (Long) request.getSession().getAttribute("teacher");
        if(tusername == null)
            return R.error("当前未登录!");
        LambdaUpdateWrapper<StudentExam> updateWrapper = new LambdaUpdateWrapper();
        updateWrapper.eq(StudentExam::getExamId,exam.getExamId())
                .eq(StudentExam::getSusername,exam.getSusername())
                .set(StudentExam::getScore,exam.getScore());
        studentExamService.update(null,updateWrapper);
        return R.success("打分成功!");
    }
}
